export const useAutoGpApiCodeGeneration = () => {
  // 生成主表字段的非空判断代码
  const generateMasterChecks = (mainTable) => {
    let checkCode = '';
    
    if (Array.isArray(mainTable.data) && mainTable.data.length > 0) {
      // 非空判断
      const nullChecks = mainTable.data
        .filter(field => field.isNull === 'Y')
        .map(field => `
            IF cl_null(${mainTable.arrayName}.${field.field}) THEN
              LET g_status.code = -1 
              LET g_status.description=g_status.description,";缺少字段 ${field.field} 请维护数据"
              LET r_success = FALSE
              EXIT WHILE        
          END IF`
        ).join('\n');
      
      checkCode += nullChecks;

      // 默认值处理
      const defaultValues = mainTable.data
        .filter(field => field.defaultValue)
        .map(field => `
          IF cl_null(${mainTable.arrayName}.${field.field}) THEN
              LET ${mainTable.arrayName}.${field.field} = "${field.defaultValue}"
          END IF`
        ).join('\n');

      if (defaultValues) {
        checkCode += '\n\n';
        checkCode += defaultValues;
      }
    }
    
    return checkCode;
  };

  // 生成主表字段解析代码
  const generateMasterFieldsParsing = (mainTable) => {
    let parseCode = '';
    if (Array.isArray(mainTable.data) && mainTable.data.length > 0) {
      mainTable.data.forEach(field => {
        if (field && field.field) {
          parseCode += `        LET ${mainTable.arrayName}.${field.field} = aws_ttsrv_getRecordField(l_node, "${field.field}")\n`;
        }
      });
    }
    return parseCode;
  };

  // 生成子表字段解析代码和检核代码
  const generateDetailFieldsParsing = (detailTables, formData) => {
    let parseCode = '';
    detailTables.forEach(table => {
      if (Array.isArray(table.data) && table.data.length > 0) {
        parseCode += `        #-------${table.name}-------#\n`;
        parseCode += `        LET l_cnt${table.arrayName} = aws_ttsrv_getDetailRecordLength(l_i, "${table.arrayName}")\n`;
        parseCode += `        FOR l_j = 1 TO l_cnt${table.arrayName}\n`;
        parseCode += `            LET l_node2 = aws_ttsrv_getDetailRecord(l_i, l_j, "${table.arrayName}")\n`;
        table.data.forEach(field => {
          if (field && field.field) {
            parseCode += `            LET ${table.arrayName}.${field.field} = aws_ttsrv_getRecordField(l_node2, "${field.field}")\n`;
          }
        });

        // 在每个子表的 END FOR 前添加检核代码
        parseCode += `            #------- ${table.name}资料检核 --------#\n`;
        parseCode += `            CALL ${formData.programId}_chk_${table.arrayName}() RETURNING l_success\n`;
        parseCode += `            IF NOT l_success THEN\n`;
        parseCode += `                LET g_status.code = -1\n`;
        parseCode += `                LET g_status.description=g_status.description,";  ${table.name}数据集检查失败"\n`;
        parseCode += `                LET g_success = 'N'\n`;
        parseCode += `                EXIT FOR\n`;
        parseCode += `            END IF\n`;
        parseCode += `            #------- ${table.name}资料检核结束 --------#\n\n`;

        // 添加写入代码
        parseCode += `            #------- ${table.name}资料写入 --------#\n`;
        parseCode += `            CALL ${formData.programId}_ins_${table.arrayName}() RETURNING l_success\n`;
        parseCode += `            IF NOT l_success THEN\n`;
        parseCode += `                LET g_status.code = -1\n`;
        parseCode += `                LET g_status.description=g_status.description,";  数据写入失败！"\n`;
        parseCode += `                LET g_success = 'N'\n`;
        parseCode += `                EXIT FOR\n`;
        parseCode += `            END IF\n`;
        parseCode += `            #------- ${table.name}资料写入结束 --------#\n`;

        parseCode += `        END FOR\n\n`;
      }
    });
    return parseCode;
  };

  // 生成子表检核代码
  const generateDetailChecks = (detailTables, formData) => {
    let checkCode = '';
    
    detailTables.forEach(table => {
      checkCode += `################################################################################\n`;
      checkCode += `# Descriptions...: ${table.name}字段检查\n`;
      checkCode += `# Memo...........: \n`;
      checkCode += `# Usage..........: CALL ${formData.programId}_chk_${table.arrayName}()\n`;
      checkCode += `# Input parameter: \n`;
      checkCode += `# Return code....: \n`;
      checkCode += `# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}\n`;
      checkCode += `# Modify.........: \n`;
      checkCode += `################################################################################\n`;
      checkCode += `FUNCTION ${formData.programId}_chk_${table.arrayName}()\n`;
      checkCode += `DEFINE r_success   LIKE type_file.num5\n`;
      checkCode += `DEFINE l_cnt       LIKE type_file.num5\n\n`;
      checkCode += `    LET r_success = TRUE\n\n`;
      checkCode += `    WHILE TRUE\n\n`;

      // 非空判定
      checkCode += `        #------- 非空判定 --------#\n`;
      if (Array.isArray(table.data)) {
        const nullChecks = table.data
          .filter(field => field.isNull === 'Y')
          .map(field => `
            IF cl_null(${table.arrayName}.${field.field}) THEN
                LET g_status.code = -1 
                LET g_status.description=g_status.description,";缺少字段 ${field.field} 请维护数据"
                LET r_success = FALSE
                EXIT WHILE        
            END IF`
          ).join('\n');
        checkCode += nullChecks;
      }
      checkCode += `\n        #------- 非空判定 --------#\n\n`;

      // 默认值处理
      checkCode += `        #------- 默认值取值 --------#\n`;
      if (Array.isArray(table.data)) {
        const defaultValues = table.data
          .filter(field => field.defaultValue)
          .map(field => `
            IF cl_null(${table.arrayName}.${field.field}) THEN
                LET ${table.arrayName}.${field.field} = "${field.defaultValue}"
            END IF`
          ).join('\n');
        checkCode += defaultValues;
      }
      checkCode += `\n        #------- 默认值取值 --------#\n\n`;

      checkCode += `        EXIT WHILE\n`;
      checkCode += `    END WHILE\n\n`;
      checkCode += `    RETURN r_success\n\n`;
      checkCode += `END FUNCTION\n\n`;
    });

    return checkCode;
  };

  // 生成主表写入代码
  const generateMasterInsert = (mainTable, formData) => {
    let insertCode = '';
    
    insertCode += `################################################################################\n`;
    insertCode += `# Descriptions...: 单头字段写入\n`;
    insertCode += `# Memo...........: \n`;
    insertCode += `# Usage..........: CALL ${formData.programId}_ins_master()\n`;
    insertCode += `# Input parameter: \n`;
    insertCode += `# Return code....: \n`;
    insertCode += `# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}\n`;
    insertCode += `# Modify.........: \n`;
    insertCode += `################################################################################\n`;
    insertCode += `FUNCTION ${formData.programId}_ins_master()\n`;
    insertCode += `DEFINE r_success   LIKE type_file.num5\n`;
    insertCode += `DEFINE l_cnt       LIKE type_file.num5\n\n`;
    insertCode += `    LET r_success = TRUE\n\n`;
    insertCode += `    IF NOT p_inTransaction THEN\n`;
    insertCode += `        BEGIN WORK\n`;
    insertCode += `    END IF\n\n`;
    
    // 生成字段对应的 INSERT 语句
    if (mainTable.insertTable && Array.isArray(mainTable.data) && mainTable.data.length > 0) {
      // 生成字段列表
      const fields = mainTable.data.map(field => field.field).join(', ');
      // 生成值列表
      const values = mainTable.data.map(field => `${mainTable.arrayName}.${field.field}`).join(', ');
      
      insertCode += `    INSERT INTO ${mainTable.insertTable} (\n`;
      insertCode += `        ${fields}\n`;
      insertCode += `    ) VALUES (\n`;
      insertCode += `        ${values}\n`;
      insertCode += `    )\n`;
      insertCode += `    IF STATUS THEN\n`;
      insertCode += `        LET g_status.code = -1\n`;
      insertCode += `        LET g_status.description=g_status.description,";写入 ${mainTable.insertTable} 失败"\n`;
      insertCode += `        LET r_success = FALSE\n`;
      insertCode += `        ROLLBACK WORK\n`;
      insertCode += `    END IF\n\n`;
    }

    insertCode += `    RETURN r_success\n\n`;
    insertCode += `END FUNCTION\n\n`;

    return insertCode;
  };

  // 生成子表写入代码
  const generateDetailInsert = (detailTables, formData) => {
    let insertCode = '';
    
    detailTables.forEach(table => {
      insertCode += `################################################################################\n`;
      insertCode += `# Descriptions...: ${table.name}字段写入\n`;
      insertCode += `# Memo...........: \n`;
      insertCode += `# Usage..........: CALL ${formData.programId}_ins_${table.arrayName}()\n`;
      insertCode += `# Input parameter: \n`;
      insertCode += `# Return code....: \n`;
      insertCode += `# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}\n`;
      insertCode += `# Modify.........: \n`;
      insertCode += `################################################################################\n`;
      insertCode += `FUNCTION ${formData.programId}_ins_${table.arrayName}()\n`;
      insertCode += `DEFINE r_success   LIKE type_file.num5\n`;
      insertCode += `DEFINE l_cnt       LIKE type_file.num5\n\n`;
      insertCode += `    LET r_success = TRUE\n\n`;
      insertCode += `    IF NOT p_inTransaction THEN\n`;
      insertCode += `        BEGIN WORK\n`;
      insertCode += `    END IF\n\n`;
      
      // 生成字段对应的 INSERT 语句
      if (table.insertTable && Array.isArray(table.data) && table.data.length > 0) {
        // 生成字段列表
        const fields = table.data.map(field => field.field).join(', ');
        // 生成值列表
        const values = table.data.map(field => `${table.arrayName}.${field.field}`).join(', ');
        
        insertCode += `    INSERT INTO ${table.insertTable} (\n`;
        insertCode += `        ${fields}\n`;
        insertCode += `    ) VALUES (\n`;
        insertCode += `        ${values}\n`;
        insertCode += `    )\n`;
        insertCode += `    IF STATUS THEN\n`;
        insertCode += `        LET g_status.code = -1\n`;
        insertCode += `        LET g_status.description=g_status.description,";写入 ${table.insertTable} 失败"\n`;
        insertCode += `        LET r_success = FALSE\n`;
        insertCode += `        ROLLBACK WORK\n`;
        insertCode += `    END IF\n\n`;
      }

      insertCode += `    RETURN r_success\n\n`;
      insertCode += `END FUNCTION\n\n`;
    });

    return insertCode;
  };

  // 主函数
  const generateAutoGpApiCode = (formData, tables) => {
    let code = '';
    
    console.log(formData)

    // 添加程序头部注释
    code += `# 程序名称: ${formData.name}\n`;
    code += `# 接口函数: ${formData.interfaceFunction}\n`;
    code += `# 撰写时间: ${new Date().toLocaleString()}\n\n`;

    code += `# 数据返回\n`;
    code += `DEFINE g_resp RECORD\n`;
    code += `    docno STRING\n`;
    code += `END RECORD\n\n`;

    code += `# 单号\n`;
    code += `DEFINE g_docno LIKE type_file.chr100\n`;
    code += `DEFINE p_inTransaction LIKE type_file.num5\n\n`;

    code += `DATABASE ds\n\n`;
    
    // 添加全局变量引用
    code += `GLOBALS "../../../tiptop/config/top.global"\n`;
    code += `GLOBALS "../../../tiptop/aws/4gl/aws_ttsrv2_global.4gl"\n\n`;
    
    // 添加 SQL 变量定义
    code += `DEFINE g_forupd_sql    STRING\n\n`;

    // 1. 先生成所有子表的类型定义
    const detailTables = tables.filter(table => table.name !== '主表');
    detailTables.forEach(table => {
      code += `TYPE ${table.tableName} RECORD\n`;
      
      if (Array.isArray(table.data) && table.data.length > 0) {
        table.data.forEach((field, index, array) => {
          if (field && field.field) {
            const refField = `${field.referenceTableField}`;
            const isLastField = index === array.length - 1;
            code += `  ${field.field.padEnd(20)} LIKE ${refField}${isLastField ? '' : ', '}  #${field.description || field.field}\n`;
          }
        });
      }
      code += `END RECORD\n\n`;
    });

    // 2. 生成子表的数组定义
    detailTables.forEach(table => {
      if (table.arrayName && table.tableName) {
        code += `DEFINE ${table.arrayName} ${table.tableName}\n`;
      }
    });
    code += '\n';

    // 3. 生成主表的类型定义
    const mainTable = tables.find(table => table.name === '主表');    
    if (mainTable) {
      code += `TYPE ${mainTable.tableName} RECORD\n`;
      
      if (Array.isArray(mainTable.data) && mainTable.data.length > 0) {
        mainTable.data.forEach((field, index, array) => {
          if (field && field.field) {
            const refField = `${field.referenceTableField}`;
            const isLastField = index === array.length - 1 && detailTables.length === 0; // 如果没有子表，这就是最后一个字段
            code += `  ${field.field.padEnd(20)} LIKE ${refField}${isLastField ? '' : ', '} #${field.description || field.field}\n`;
          }
        });
      }
      
      // 添加子表数组
      detailTables.forEach((childTable, index) => {
        if (childTable.arrayName && childTable.tableName) {
          const isLast = index === detailTables.length - 1;
          code += `  ${childTable.arrayName.padEnd(20)} DYNAMIC ARRAY OF ${childTable.tableName}${isLast ? '' : ','}\n`;
        }
      });
      code += `END RECORD\n\n`;
    }

    // 4. 定义主表
    if (mainTable && mainTable.tableName) {
      code += `DEFINE g_master ${mainTable.tableName}\n\n`;
    }


    // 添加主函数
    code += `################################################################################\n`;
    code += `# Descriptions...: 接口入口\n`;
    code += `# Memo...........:\n`;
    code += `# Usage..........: CALL ${formData.interfaceFunction}()\n`;
    code += `# Input parameter:\n`;
    code += `# Return code....:\n`;
    code += `# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}\n`;
    code += `# Modify.........:\n`;
    code += `################################################################################\n`;
    
    code += `FUNCTION ${formData.interfaceFunction}()\n`;
    code += `    WHENEVER ERROR CONTINUE\n`;
    code += `    CALL aws_ttsrv_preprocess()\n`;
    code += `    IF g_status.code = "0" THEN\n`;
    code += `        CALL ${formData.interfaceFunction}_process()\n`;
    code += `    END IF\n`;
    code += `    CALL aws_ttsrv_postprocess()\n`;
    code += `END FUNCTION\n\n`;

    code += `################################################################################\n`;
    code += `# Descriptions...: 执行主干程序\n`;
    code += `# Memo...........:\n`;
    code += `# Usage..........: CALL ${formData.interfaceFunction}_process()\n`;
    code += `# Input parameter: \n`;
    code += `# Return code....: \n`;
    code += `# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}\n`;
    code += `# Modify.........:\n`;
    code += `################################################################################\n`;
    code += `FUNCTION ${formData.interfaceFunction}_process()\n`;
    code += `    DEFINE l_param          RECORD\n`;
    code += `          ${mainTable.arrayName}     DYNAMIC ARRAY OF ${mainTable.tableName}\n`;
    code += `    END RECORD\n`;
    code += `    DEFINE l_i,l_j,l_n,l_t             LIKE type_file.num10\n`;
    code += `    DEFINE l_cnt,l_cnt1,l_cnt2,l_cnt3,l_cnt5,l_cnt6     LIKE type_file.num10\n`;
    code += `    DEFINE l_node,l_node1,l_node2          om.DomNode\n`;
    code += `    DEFINE l_docno         LIKE type_file.chr100\n`;
    code += `    DEFINE l_type          LIKE type_file.chr100\n`;
    code += `    DEFINE l_code          LIKE type_file.chr100\n`;
    code += `    DEFINE l_date          LIKE type_file.dat\n`;
    code += `    DEFINE l_chr           LIKE type_file.chr50\n`;
    code += `    DEFINE li_result       LIKE type_file.num5\n`;
    code += `    DEFINE l_sql           STRING\n`;
    code += `    DEFINE l_success       LIKE type_file.num5\n\n`;

    code += `    LET g_success = 'Y'\n`;
    code += `    INITIALIZE g_resp.* TO NULL\n\n`;

    // 判断是否有数据
    code += `    LET l_cnt = aws_ttsrv_getMasterRecordLength("${mainTable.arrayName}")\n`;
    code += `    IF l_cnt = 0 THEN\n`;
    code +=`        LET g_status.code = "-1"\n`;
    code +=`        LET g_status.description = "No recordset processed!"\n`;
    code +=`        RETURN\n`;
    code +=`    END IF\n\n`;

    //-------料开始获取 --------#
    code += `    BEGIN WORK\n\n`;
    code += `    FOR l_i = 1 TO l_cnt\n`;
    code += `        INITIALIZE ${mainTable.arrayName}.* TO NULL\n`;
    code += `        LET l_node = aws_ttsrv_getMasterRecord(l_i, "${mainTable.arrayName}")\n\n`;
    
    //------- 解析单头字段 --------#
    code += `        #------- 解析单头字段 --------\n`;
    code += generateMasterFieldsParsing(mainTable);
    code += '\n';

    code += `        #------- 单头资料检核 --------#\n`;
    code += `        CALL ${formData.programId}_chk_master() RETURNING l_success\n`;
    code += `        IF NOT l_success THEN\n`;
    code += `            LET g_status.code = -1\n`;
    code += `            LET g_status.description=g_status.description,";  数据集检查失败"\n`;
    code += `            LET g_success = 'N'\n`;
    code += `            EXIT FOR\n`;
    code += `        END IF\n\n`;

    code += `        #------- 单头资料写入 --------#\n`;
    code += `        CALL ${formData.programId}_ins_master() RETURNING l_success\n`;
    code += `        IF NOT l_success THEN\n`;
    code += `            LET g_status.code = -1\n`;
    code += `            LET g_status.description=g_status.description,";  数据新增失败"\n`;
    code += `            LET g_success = 'N'\n`;
    code += `            EXIT FOR\n`;
    code += `        END IF\n\n`;


    //------- 解析单身字段 --------#
    if (detailTables.length > 0) {
        code += generateDetailFieldsParsing(detailTables, formData);
    }

    //------- 单号返回 --------#
    code += `        END FOR\n\n`;
    code += `        #------- 单号返回 --------#\n`;
    code += `        IF cl_null(g_resp.docno) THEN\n`;
    code += `            LET g_resp.docno = g_docno\n`;
    code += `        ELSE\n`;
    code += `            LET g_resp.docno = g_resp.docno,"|",g_docno\n`;
    code += `        END IF\n\n`;
    
    //------- 事务判定 --------#
    code += `        #------- 事务判定 --------#\n`;
    code += `        IF g_success= 'Y' THEN\n`;
    code += `            COMMIT WORK\n`;
    code += `            LET g_status.code = 0\n`;
    code += `            LET g_status.description = "资料产生成功"\n`;
    code += `            CALL aws_ttsrv_addParameterRecord(base.TypeInfo.create(g_resp))\n`;
    code += `        ELSE\n`;
    code += `            ROLLBACK WORK\n`;
    code += `        END IF\n\n`;

    code += `END FUNCTION\n`;


    code += `################################################################################\n`;
    code += `# Descriptions...: 单头字段检查\n`;
    code += `# Memo...........:\n`;
    code += `# Usage..........: CALL ${formData.programId}_chk_master()\n`;
    code += `# Input parameter:  \n`;
    code += `# Return code....: \n`;
    code += `# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}\n`;
    code += `# Modify.........:\n`;
    code += `################################################################################\n`;
    code += `FUNCTION ${formData.programId}_chk_master()\n`;
    code += `    DEFINE r_success   LIKE type_file.num5\n`;
    code += `    DEFINE l_cnt       LIKE type_file.num5\n\n`;
    code += `    LET r_success = TRUE\n\n`;
    code += `    WHILE TRUE\n`;
    code += `        #------- 非空判定 --------#`;
    code += generateMasterChecks(mainTable);
    code += `        EXIT WHILE\n`;
    code += `    END WHILE\n\n`;
    code += `    RETURN r_success\n\n`;
    code += `END FUNCTION\n\n`;

    // 在生成主表检核函数后，添加子表检核函数
    if (detailTables.length > 0) {
      code += generateDetailChecks(detailTables, formData);
    }

    // 在生成主表检核函数后，添加主表写入函数
    if (mainTable) {
      code += generateMasterInsert(mainTable, formData);
    }

    // 在生成主表写入函数后，添加子表写入函数
    if (detailTables.length > 0) {
      code += generateDetailInsert(detailTables, formData);
    }

    // 生成请求报文格式示例
    code += `################################################################################\n`;
    code += `# Request XML Format:\n`;
    code += `################################################################################\n`;
    code += `    {
        <Request>
            <Access>
                <Authentication user="tiptop" password="tiptop"/>
                <Connection application="ERP"/>
                <Organization name="NNJLH"/>
                <Locale language="zh_cn"/>
            </Access>
            <RequestContent>
                <Parameter>
                    <Record></Record>
                </Parameter>
                <Document>
                    <RecordSet id="1">
                        <Master name="${mainTable.insertTable}">
                            <Record>\n`;

    // 生成主表字段的XML格式
    if (mainTable && Array.isArray(mainTable.data)) {
        mainTable.data.forEach(field => {
            code += `                                <Field name="${field.field}" value=""/>\n`;
        });
    }

    code += `                            </Record>
                        </Master>\n`;

    // 生成子表字段的XML格式
    if (detailTables.length > 0) {
        detailTables.forEach(table => {
            code += `                        <Detail name="${table.insertTable}">
                            <Record>\n`;
            if (Array.isArray(table.data)) {
                table.data.forEach(field => {
                    code += `                                <Field name="${field.field}" value=""/>\n`;
                });
            }
            code += `                            </Record>
                        </Detail>\n`;
        });
    }

    code += `                    </RecordSet>
                </Document>
            </RequestContent>
        </Request>
    }\n#\n`;

    // 生成响应报文格式示例
    code += `################################################################################\n`;
    code += `# Response XML Format:\n`;
    code += `################################################################################\n`;
    code += `    {
        <Response>
            <Execution>
                <Status code="0" sglcode="0" description="单据生成成功"/>
            </Execution>
            <ResponseContent>
                <Parameter>
                    <Record>
                        <Field name="doc_no" value="单号"/>
                    </Record>
                </Parameter>
                <Document/>
            </ResponseContent>
        </Response>
    }\n\n`;

    return code;
  };

  return {
    generateAutoGpApiCode
  };
};